#include "window.h"

int window_init(struct window* w)
{
    w->hwnd = NULL;
    w->edit = NULL;
    w->menu = NULL;
    w->button = NULL;
    w->font = NULL;
    return 0;
}

int window_create(struct window* w, const WNDCLASSEXW* wnd, int cmd_show)
{
    if (!RegisterClassEx(wnd))
    {
        return -1;
    }

    w->font = GetStockObject(DEFAULT_GUI_FONT);
    w->hwnd = CreateWindowEx(0, L"tryicon", L"tryicon", WS_OVERLAPPEDWINDOW, 800, 200, 440, 480, NULL, NULL, wnd->hInstance, w);
    w->edit = CreateWindow(L"edit", L"", WS_CHILD | WS_VISIBLE | ES_MULTILINE | WS_BORDER | WS_VSCROLL | WS_HSCROLL, 0, 30, 400, 400, w->hwnd, 0, NULL, NULL) ;
    w->button = CreateWindow(L"button", L"Check now", WS_CHILD | WS_VISIBLE , 2, 2, 80, 26, w->hwnd, (HMENU)ID_CHECK_NOW, NULL, NULL) ;

    SendMessage(w->edit, WM_SETFONT, (WPARAM)w->font, (LPARAM)0);
    SendMessage(w->button, WM_SETFONT, (WPARAM)w->font, (LPARAM)0);

    SetWindowLongPtr(w->hwnd, GWLP_USERDATA, (LONG)w);

    ShowWindow(w->hwnd, cmd_show);

    return 0;
}

int window_on_create(struct window* w)
{
    w->menu = CreatePopupMenu();
    AppendMenu(w->menu, MF_STRING, ID_TRAY_HIDE_CONTEXT_MENU_ITEM, L"Hide");
    AppendMenu(w->menu, MF_STRING, ID_TRAY_SHOW_CONTEXT_MENU_ITEM, L"Show");
    AppendMenu(w->menu, MF_STRING, ID_TRAY_EXIT_CONTEXT_MENU_ITEM, L"Exit");
    return 0;
}

void window_minimize(struct window* w)
{
    ShowWindow(w->hwnd, SW_HIDE);
}

void window_restore(struct window* w)
{
    ShowWindow(w->hwnd, SW_SHOW);
}

void window_track_menu(struct window* w)
{
    POINT curPoint ;
    UINT clicked;

    GetCursorPos(&curPoint) ;
    SetForegroundWindow(w->hwnd);
    clicked = TrackPopupMenu(w->menu, TPM_RETURNCMD | TPM_NONOTIFY, curPoint.x, curPoint.y, 0, w->hwnd, NULL);

    switch (clicked)
    {
    case ID_TRAY_EXIT_CONTEXT_MENU_ITEM:
        DestroyWindow(w->hwnd);
        break;

    case ID_TRAY_SHOW_CONTEXT_MENU_ITEM:
        window_restore(w);
        break;

    case ID_TRAY_HIDE_CONTEXT_MENU_ITEM:
        window_minimize(w);
        break;
    }
}

void window_append_text(struct window* w, const wchar_t* ustr)
{
    int nLength = GetWindowTextLength(w->edit);

    if (nLength > 1000)
    {
        SendMessage(w->edit, EM_SETSEL, 0, (LPARAM) - 1);
    }
    else
    {
        SendMessage(w->edit, EM_SETSEL, (WPARAM)nLength, (LPARAM)nLength);
    }
    SendMessage(w->edit, EM_REPLACESEL, (WPARAM)FALSE, (LPARAM)ustr);
}

int window_size(struct window* w, int cmd, int x, int y)
{
    MoveWindow(w->edit, 0, 30, x, y - 30, TRUE);
    return 0;
}
